import 'dart:async';

import 'package:github/server.dart';

import 'github_repo.dart';

class NotificationRepo with Repo {
  static NotificationRepo _instance;

  NotificationRepo._() {
    init();
  }

  factory NotificationRepo() {
    if (_instance == null) {
      _instance = NotificationRepo._();
    }
    return _instance;
  }

  StreamController<List<Notification>> _notificationController =
      StreamController();

  Stream<List<Notification>> notificationStream;

  set notification(List<Notification> obj) {
    _notification = obj;
    _notificationController.add(obj);
  }

  List<Notification> _notification = [];

  List<Notification> get notification => _notification;

  void init() {
    notificationStream = _notificationController.stream.asBroadcastStream();
  }

  Set<String> _ids = Set();

  void refresh() {
    print(_ids);
    client.activity.listNotifications(all: true).asBroadcastStream().listen(
      (notification) {
        _notify();
        if (_ids.contains(notification.id)) {
          return;
        }
        _notification.add(notification);
        _ids.add(notification.id);
        this._notification.sort((n1, n2) {
          var difference = n1.updatedAt.difference(n2.updatedAt);
          if (difference == Duration.zero) {
            return 0;
          }
          return difference.isNegative ? 1 : -1;
        });
        _notify();
      },
    );
  }

  _notify() {
    _notificationController.add(notification);
  }
}
